package geguol.cc.widgetapplication.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.List;

import geguol.cc.widgetapplication.R;
import geguol.cc.widgetapplication.widget.SearchDropListView;

/**
 * 作者  格锅
 * 时间  2016/12/14 15:46
 * 描述  自带过滤功能的Adapter
 */

public abstract class AutoCompleteBaseAdapter<T extends SearchDropListView.SearchBean> extends BaseAdapter implements Filterable {
	ArrayList<T> dataList=new ArrayList<>();
	public AutoCompleteBaseAdapter(Context context) {
		this.context = context;
	}
	Context context;
	DBFilter filter;
	@Override
	public int getCount() {
		return dataList.size();
	}

	@Override
	public T getItem(int position) {
		return dataList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		if (convertView==null){
			convertView= View.inflate(context, R.layout.account_list_item,null);
		}
		TextView items= (TextView) convertView.findViewById(R.id.list_item);
		T temp = dataList.get(position);
		items.setText(temp.getText());
		return convertView;
	}
	/**
	 * 获取过滤器
	 */
	@Override
	public Filter getFilter() {
		if (filter == null) {
			filter = new DBFilter();
		}
		return filter;
	}
	// 获取列表集合
	public List<T> getList(){
		return dataList;
	}

	public void  setList(List list){
		if (list==null)return;
		dataList.clear();
		dataList.addAll(list);
	}

	public abstract List<T> getNewDataSources(CharSequence prefix);//新建过滤规则

	/**
	 * 数据库查询过滤器
	 *
	 * @author Administrator
	 *
	 */
	private class DBFilter extends Filter {
		/**
		 * 至少要输入两个字母才能获取到文字
		 */
		@Override
		protected FilterResults performFiltering(CharSequence prefix) {
			//查询结果保存到FilterResults对象里
			FilterResults results = new FilterResults();
			List<T> datas= getNewDataSources(prefix);
			results.values=datas;
			results.count = datas.size();
			return results;
		}

		/**
		 * 更新UI
		 */
		@Override
		protected void publishResults(CharSequence constraint, FilterResults results) {
			List<T> queryAll = (List<T>) results.values;
			if (queryAll != null && queryAll.size() > 0){
				dataList.clear();
				dataList.addAll(queryAll);
				notifyDataSetChanged();
			}
		}

		@Override
		public CharSequence convertResultToString(Object resultValue) {
			return ((T)resultValue).getText();
		}
	}
}
